package com.yuyou.fn.educational.service.impl;

import com.github.wens.mybatisplus.examples.Example;
import com.github.wens.mybatisplus.plugins.Page;
import com.yuyou.fn.common.exception.BusException;
import com.yuyou.fn.common.util.Threads;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.educational.entity.CourseClass;
import com.yuyou.fn.educational.entity.CourseOrder;
import com.yuyou.fn.educational.service.IAttendanceRecordService;
import com.yuyou.fn.educational.service.ICourseClassService;
import com.yuyou.fn.educational.service.ICourseOrderService;
import com.yuyou.fn.common.util.BeanUtils;
import com.yuyou.fn.common.util.CriteriaUtils;
import com.yuyou.fn.educational.vo.*;
import com.yuyou.fn.settlement.service.ISettlementService;
import org.springframework.stereotype.Service;

import com.yuyou.fn.educational.mapper.StudentRegMapper;
import com.yuyou.fn.educational.entity.StudentReg;
import com.yuyou.fn.educational.service.IStudentRegService;
import com.github.wens.framework.service.impl.SuperServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * @author Terry
 *         StudentReg 表数据服务层接口实现类
 */
@Service
public class StudentRegServiceImpl extends SuperServiceImpl<StudentRegMapper, StudentReg, Long> implements IStudentRegService {

    @Resource
    private ICourseClassService courseClassService;


    @Resource
    private ICourseOrderService courseOrderService;

    @Resource
    private ISettlementService settlementService;


    @Resource
    private IAttendanceRecordService attendanceRecordService ;



    /**
     * 注册列表
     *
     * @param studentRegQueryVo
     * @return
     */
    @Override
    public List<StudentReg> findStudentRegQuery(StudentRegQueryVo studentRegQueryVo) {
        Example<StudentReg> example = StudentReg.createExample();
        example.orderBy("updateTime").desc();
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria, studentRegQueryVo);
        return findListByExample(example);
    }


    /**
     * 根据订单编号查询注册信息
     *
     * @param courseOrderId
     * @return
     */
    @Override
    public List<StudentReg> findStudentRegByCourseOrderId(Long courseOrderId) {
        Example<StudentReg> example = StudentReg.createExample();
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("courseOrderId" , courseOrderId );
        return findListByExample(example);
    }



    @Override
    public void changeStudentRegCharging(Long courseOrderId ,BigDecimal payableAmount , BigDecimal paidAmount, Integer chargingStatus) {

        List<StudentReg> studentRegList = findStudentRegByCourseOrderId(courseOrderId) ;

        for(StudentReg studentReg : studentRegList ){

            StudentReg update = new StudentReg();
            update.setRegId(studentReg.getRegId());
            update.setChargingStatus(chargingStatus);
            if(chargingStatus == 2 ){//已经支付
                update.setPayAmount(studentReg.getTotalAmount());
            }else if(chargingStatus == 1 || chargingStatus == 0 ){//欠费
                //计算支付比例
                update.setPayAmount(Utils.calProportion(paidAmount ,studentReg.getTotalAmount() , payableAmount ));
            }else {

            }
            updateSelectiveById(update) ;
        }


    }

    @Override
    public TurnClassVo courseClassDetail(Long regId) {
        TurnClassVo vo = new TurnClassVo();
        StudentReg studentReg = findById(regId);
        CourseClass courseClass = courseClassService.findById(studentReg.getClassId());
        BeanUtils.copyProperties(vo,studentReg);
        BeanUtils.copyProperties(vo,courseClass);
        return vo;
    }

    /**
     * 确认转班
     *
     * @param regId
     */
    @Override
    public RefundApplyVo refundApplyMessage(Long regId) {
        RefundApplyVo refundApplyVo = new RefundApplyVo();
        StudentReg studentReg = findById(regId);
        CourseClass courseClass = courseClassService.findById(studentReg.getClassId());
        BeanUtils.copyProperties(refundApplyVo, studentReg);
        BeanUtils.copyProperties(refundApplyVo, courseClass);
        return refundApplyVo;
    }

    @Transactional
    @Override
    public void changeClass(ChooseClassVo chooseClassVo) {

        StudentReg oldStudentReg = findById(chooseClassVo.getRegId());
        CourseClass oldCourseClass = courseClassService.findById(chooseClassVo.getOldClassId());
        CourseClass courseClass = courseClassService.findById(chooseClassVo.getClassId());

        if( 2 != oldStudentReg.getChargingStatus() && !oldCourseClass.getStudyingFee().equals(courseClass.getStudyingFee()) && !oldCourseClass.getLectureAmount().equals(courseClass.getLectureAmount())){
            throw new BusException("不符合转班要求");
        }

        //原注册信息注册状态改成转班
        changeRegStatus(chooseClassVo.getRegId(),1);

        BigDecimal refundAmount = oldStudentReg.getPayAmount();//退款金额

        settlementService.bookRefundForCourse( oldCourseClass.getBusTeamId(), oldStudentReg.getStudentId() , refundAmount , oldCourseClass.getClassName()  ,oldCourseClass.getClassId() , oldStudentReg.getRegId() );

        //原班级信息的报名人数减一
        courseClassService.decreaseRegAmount(chooseClassVo.getOldClassId());
        //删除考勤记录
        attendanceRecordService.deleteAttendanceRecordForStudent(oldStudentReg.getClassId(),oldStudentReg.getStudentId(),chooseClassVo.getStartAmount(),chooseClassVo.getEndAmount());

        StudentRegInfoVo studentRegInfoVo = new StudentRegInfoVo();
        studentRegInfoVo.setFrom(0);
        studentRegInfoVo.setOperator("");
        RegClassInfoVo regClassInfoVo = new RegClassInfoVo();
        regClassInfoVo.setClassId(chooseClassVo.getClassId());
        regClassInfoVo.setStartAmount(chooseClassVo.getStartAmount());
        regClassInfoVo.setEndAmount(chooseClassVo.getEndAmount());
        studentRegInfoVo.setRegClassInfoList(Arrays.asList(regClassInfoVo));
        studentRegInfoVo.setStudentId(oldStudentReg.getStudentId());
        CourseOrder courseOrder = courseOrderService.createOrder(studentRegInfoVo);
        courseOrderService.payCourseOrder(courseOrder.getCourseOrderId(),refundAmount,3,"");
    }

    /**
     * 根据注册表id，修改注册状态
     *
     * @param regId
     * @param regStatus（0-在读；1-转班；2-退账户；3-退班退费）
     */
    @Override
    public void changeRegStatus(Long regId, Integer regStatus) {
        StudentReg studentReg = new StudentReg();
        studentReg.setRegId(regId);
        studentReg.setRegStatus(regStatus);
        updateSelectiveById(studentReg);
    }

    @Override
    public Page<StudentReg> findStudentRegByQuery(StudentRegQueryVo studentRegQueryVo, int pageNo, int pageSize) {
        Example<StudentReg> example = StudentReg.createExample();
        example.orderBy("createTime").desc();
        Example.Criteria criteria = example.createCriteria();
        CriteriaUtils.fillCondition(criteria , studentRegQueryVo);
        return findPageByExample(example,pageNo,pageSize );
    }

    @Override
    public boolean hadReg(Long classId, Long studentId) {
        Example<StudentReg> example = StudentReg.createExample();
        example.createCriteria().andEqualTo("classId",classId).andEqualTo("studentId",studentId );
        return this.countByExample(example) > 0 ? true : false ;
    }

    @Override
    public void changeRefundStatus(Long regId, int status) {
        StudentReg studentReg = new StudentReg();
        studentReg.setRegId(regId);
        studentReg.setRefundStatus(status);
        updateSelectiveById(studentReg);
    }

    @Override
    public void saveStudentReg(final List<StudentReg> studentRegList) {
        insertBatch(studentRegList);
        Threads.dispatch(new Runnable() {
            @Override
            public void run() {
                attendanceRecordService.createAttendanceRecordForStudent(studentRegList);
            }
        });

    }

    @Override
    public List<StudentReg> findStudentClassIds(Long studentId,List<String> regStatus) {
        Example<StudentReg> example=StudentReg.createExample();
        example.selectProperties("classId");
        example.setDistinct(true);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("studentId",studentId);
        criteria.andIn("regStatus",regStatus);
        return   findListByExample(example);
    }

    @Override
    public List<StudentReg> findStudentRegByStudentIds(List<Long> studentIdList, List<String> regStatusList) {
        Example<StudentReg> example=StudentReg.createExample();
        Example.Criteria criteria=example.createCriteria();
        criteria.andIn("studentId",studentIdList);
        if (regStatusList.size()>0)
            criteria.andIn("regStatus",regStatusList);
        return   findListByExample(example);
    }

}